package org.jeecg.modules.commonmode.reldateweek.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.common.utils.DateUtil;
import org.jeecg.modules.common.utils.StringUtil;
import org.jeecg.modules.commonmode.reldateweek.entity.RelDateWeek;
import org.jeecg.modules.commonmode.reldateweek.mapper.RelDateWeekMapper;
import org.jeecg.modules.commonmode.reldateweek.service.IRelDateWeekService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.util.Assert;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: rel_date_week
 * @author: baochangrong
 * @Date: 2022-04-11
 * @Version: V1.0
 */
@Service
public class RelDateWeekServiceImpl extends ServiceImpl<RelDateWeekMapper, RelDateWeek> implements IRelDateWeekService {

    @Autowired
    public RelDateWeekMapper relDateWeekMapperImpl;

    public Result saveRelDateWeek(String years) {

        SimpleDateFormat dateFm = new SimpleDateFormat("YYYY");
        String year =dateFm.format(new Date());
        if(!StringUtil.isEmpty(years)){
            year = years;
        }
        JSONArray data = DateUtil.queryDateWeek(year);
        Assert.notEmpty(data, "系统获取节假日信息异常，请检查网络。并联系管理员");

        Map yearInfo = new HashMap();
        yearInfo.put("year", year);
        //清理当前传入年份的数据
        relDateWeekMapperImpl.deleteYear(yearInfo);
        for (int dataIndex = 0; dataIndex < data.size(); dataIndex++) {
            JSONArray dataArray = data.getJSONArray(dataIndex);
            for (int dataArrayIndex = 0; dataArrayIndex < dataArray.size(); dataArrayIndex++) {
                JSONObject relDateWeeks = dataArray.getJSONObject(dataArrayIndex);
                RelDateWeek relDateWeek = JSONObject.toJavaObject(relDateWeeks, RelDateWeek.class);
                relDateWeek.setDateTime(relDateWeeks.getString("date"));
                int flage = relDateWeekMapperImpl.insert(relDateWeek);
                if (flage < 1) {
                    new IllegalArgumentException("写入失败！");
                    return Result.error("执行失败！");
                }
            }
        }
            return Result.OK("执行成功！");

    }

}
